<template>
  <div class="login-view">

  </div>

</template>

<script>
export default {
  name: 'AutoLogin',

  data() {
    return {
      loginForm: {
        terminal: this.$enums.TERMINAL_TYPE.WEB,
        userName: '',
        password: '',
        nickName: ''
      },
      loadingInstance: null,
      avatar: ''
    }
  },
  methods: {
    loading() {
      this.loadingInstance = this.$loading({
        lock: true,
        // text: '加载中...',
        spinner: 'el-icon-loading'
        // background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    handleMessage(event) {
      // console.log('login', event.data)
      // 这里可以添加验证 event.origin 来确保安全
      if (event.data && event.data.userName) {
        this.loginForm.userName = event.data.userName
        // this.loginForm.password = event.data.password
        this.loginForm.nickName = event.data.nickName || event.data.userName
        this.avatar = event.data.avatar
       const accessToken = localStorage.getItem('accessToken')
        if (accessToken) {
          this.$router.push('/home/chat')
        } else {
          this.autoLogin()
        }
        
      }
    },
    autoLogin() {
      this.loading()
      this.$http({
        url: '/login',
        method: 'post',
        data: this.loginForm
      }).then(data => {
        // 保存密码到cookie(不安全)
        // this.setCookie('username', this.loginForm.userName)
        // this.setCookie('password', this.loginForm.password)
        // 保存token
        // sessionStorage.setItem('accessToken', data.accessToken)
        // sessionStorage.setItem('refreshToken', data.refreshToken)
        localStorage.setItem('accessToken', data.accessToken)
        localStorage.setItem('refreshToken', data.refreshToken)
        this.$store.commit('setUserAvatar', this.avatar)
        this.$router.push('/home/chat')
        this.loadingInstance.close()
      })
    }
  },
  mounted() {
    // this.loginForm.userName = this.getCookie('username')
    // cookie存密码并不安全，暂时是为了方便
    // this.loginForm.password = this.getCookie('password')
    const userName = this.$route.query.userName;
    const nickName = this.$route.query.nickName;
    if (userName) {
      this.handleMessage({data: {userName: userName, nickName: nickName}});
    }
    // 监听来自父页面的消息
    window.addEventListener('message', this.handleMessage)
  },
  beforeDestroy() {
    // 清除事件监听器
    window.removeEventListener('message', this.handleMessage)
  }
}
</script>

<style scoped lang="scss">
</style>
